﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.Preferences;
using ApplicationLibrary.SqlConnector;
using Plumber.Sales.ModuleData;

namespace Plumber.Sales.Forms
{
    public partial class Sentences : DocumentForm
    {
        private PreferencesManager<NHUnspellPref> myLanguage = null;
        private NHUnspellPref NHUnspellPref = null;
        private BindableOject<int> ID = new BindableOject<int>();

        public Sentences()
            : base(Properties.Resources.FN_Sentences)
        {
            InitializeComponent();
            myLanguage = new PreferencesManager<NHUnspellPref>(formName, null);
            NHUnspellPref = myLanguage.ReadPreference();
            if (NHUnspellPref.Enable)
                rtbDescription.Language = NHUnspellPref.Language;
            else
                rtbDescription.SpellingEnable = false;
        }

        protected override void OnLoad(EventArgs e)
        {
            LoadFields();
            base.OnLoad(e);
        }

        #region Virtual Method

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarSentencesParam(ID.ToString());
        }

        protected override void OnAttachData()
        {
            dbManager = new dbmanagerSentences("sentenceForm", new RadarSentences(), this);
            dbManager.AddMaster(this, PL_Sentences.Name, true);
        }

        protected override void OnBindData()
        {
            BindObject(ID, PL_Sentences.ID);
            BindControl(txtTitle, PL_Sentences.Title);
            BindControl(rtbDescription, PL_Sentences.Text, "Rtf");
            BindControl(trvField);
        }

        protected override bool OnBeforeSave()
        {
            if (txtTitle.Text.Equals(string.Empty))
            {
                MyMessageBox(this, Properties.Resources.Msg_TxtTitle,
                    Properties.Resources.Error,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return base.OnBeforeSave();
        }

        protected override void FocusOnNew()
        {
        }

        protected override void OnDisableControlsForEdit()
        {
        }

        #endregion

        #region Events

        #endregion

        private void LoadFields()
        {
            // Creates the ResourceManager.
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(Properties.Resources.FieldDescription);

            XmlNodeList xtables = xDoc.GetElementsByTagName("table");

            foreach (XmlNode xtable in xtables)
            {
                string myTable = Properties.Resources.ResourceManager.GetString(xtable.Attributes["description"].Value);
                TreeNode tNode = trvField.Nodes.Add(myTable);

                foreach (XmlNode xfield in xtable.ChildNodes)
                {
                    string myField = Properties.Resources.ResourceManager.GetString(xfield.Attributes["description"].Value);
                    tNode.Nodes.Add(myField);
                }
            }
        }

        private void trvField_MouseDown(object sender, MouseEventArgs e)
        {
            TreeNode nodeclick = trvField.GetNodeAt(e.X, e.Y);
            if (e.Button != MouseButtons.Left)
                nodeclick = null;

            if (nodeclick != null && nodeclick.Parent != null)
            {
                string text = string.Format("{{{0}.{1}}}", nodeclick.Parent.Text, nodeclick.Text);
                DoDragDrop(text, DragDropEffects.Copy);
            }
        }

        //private void txtDescription_DragDrop(object sender, DragEventArgs e)
        //{
        //    String str = (String)e.Data.GetData(DataFormats.StringFormat);
        //    int pos = GetCaretIndexFromPoint(txtDescription, e.X, e.Y);
        //        //txtDescription.GetCharIndexFromPosition(txtDescription.PointToClient(new Point(e.X, e.Y)));

        //    txtDescription.Text = txtDescription.Text.Substring(0, pos) +
        //        str + txtDescription.Text.Substring(pos, txtDescription.Text.Length - pos);
        //}

        //private void txtDescription_DragEnter(object sender, DragEventArgs e)
        //{
        //    e.Effect = e.Data.GetDataPresent(DataFormats.StringFormat)
        //                     ? DragDropEffects.Copy
        //                     : DragDropEffects.None;
        //}

        private int GetCaretIndexFromPoint(TextBox tb, int x, int y)
        {
            Point p = tb.PointToClient(new Point(x, y));
            int i = tb.GetCharIndexFromPosition(p);
            if (i == tb.Text.Length - 1)
            {
                Point c = tb.GetPositionFromCharIndex(i);
                if (p.X > c.X)
                    i++;
            }
            return i;
        }

        private void rtbDescription_RicherDragEnter(object sender, DragEventArgs e)
        {
            e.Effect = e.Data.GetDataPresent(DataFormats.Rtf)
                             ? DragDropEffects.Copy
                             : DragDropEffects.None;
        }

        private void rtbDescription_RicherDragOver(object sender, DragEventArgs e)
        {
            e.Effect = e.Data.GetDataPresent(DataFormats.Rtf)
                             ? DragDropEffects.Copy
                             : DragDropEffects.None;
        }
    }

    #region DbManager Sentences

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    internal class dbmanagerSentences : DBManager
    {
        public dbmanagerSentences(string name, RadarForm radar, DocumentForm document)
            : base(name, radar, document)
        {
        }

        protected override void dAdapter_MasterRowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            base.dAdapter_MasterRowUpdating(sender, e);
        }

        protected override string CreateMasterQuery()
        {
            this.Table = new PL_Sentences();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(this.Table);
            qB.AddCompare(PL_Sentences.ID, "@p1");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter sParam = new SqlABParameter("@p1", PL_Sentences.ID);
            sParam.Value = 0;
            PList.Add(sParam);
            return PList;
        }

        protected override void SetParameters(ApplicationLibrary.ExtendedControls.IRadarParameters key, DBCollection collection)
        {
            collection.Parameter[0].Value = key.GetValue<int>(0) == 0 ? GetLastID() : key.GetValue<int>(0);
        }

        private int GetLastID()
        {
            DRMAXIDSentences drMAxID = new DRMAXIDSentences();
            drMAxID.Find();
            return drMAxID.GetValue<int>(PL_Sentences.ID);
        }
    }

    #endregion
}